import { useEffect } from 'react';
import PropTypes from 'prop-types';
import OHIF from '@ohif/core';
import { useDispatch } from 'react-redux';

const {
  setStudyLoadingProgress,
  clearStudyLoadingProgress
} = OHIF.redux.actions;

const  StudyLoadingMonitor = ({ studies }) => {
  const dispatch = useDispatch();
  const options = {
    _setProgressData: (progressId, progressData) => {
      dispatch(setStudyLoadingProgress(progressId, progressData));
    },
    _clearProgressById: progressId => {
      dispatch(clearStudyLoadingProgress(progressId));
    },
  };

  const { StudyLoadingListener } = OHIF.classes;
  const studyLoadingListener = StudyLoadingListener.getInstance(options);

  useEffect(() => {
    studyLoadingListener.addStudies(studies);
    return () => {
      studyLoadingListener.clear();
    }
  }, [studies]);

  return null;
}

StudyLoadingMonitor.propTypes = {
  studies: PropTypes.array.isRequired,
};

export default StudyLoadingMonitor;
